package com.gali.juc;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Auther: gali
 * @Date: 2022-08-18 20:14
 * @Description:
 */
public class CompletableFutureMall {
    static List<NetMall> list= Arrays.asList(
            new NetMall("jd"),
            new NetMall("taobao"),
            new NetMall("dangdang")
    );

    /**
     * step by step
     * @param list
     * @param productName
     * @return
     */
    public static List<String> getPrice(List<NetMall> list,String productName){
        return list.stream().map(netMall -> String.format(productName + "in %s price is %.2f",
                netMall.getNetMallName(),
                netMall.cartPrice(productName))).collect(Collectors.toList());
    }

    /**
     * all in
     * @param list
     * @param productName
     * @return
     */
    public static List<String> getPriceCompletableFuture(List<NetMall> list,String productName){
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> String.format(productName + "in %s price is %.2f",
                netMall.getNetMallName(),
                netMall.cartPrice(productName)))).collect(Collectors.toList())
                .stream()
                .map(stringCompletableFuture -> stringCompletableFuture.join()).collect(Collectors.toList());
    }
    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        List<String> list1=getPriceCompletableFuture(list,"mysql");
        for(String element:list1){
            System.out.println(element);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("消耗的时间是："+(endTime-startTime)+"毫秒");
    }
}
class NetMall{
    @Getter
    private String netMallName;

    public NetMall(String netMallName){
        this.netMallName=netMallName;
    }
    public double cartPrice(String productName){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // System.out.println(ThreadLocalRandom.current().nextDouble() * 2 + "mysql".charAt(0));  结果为：110.87523381811312
       return ThreadLocalRandom.current().nextDouble()*2+productName.charAt(0);
    }
}

